﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using XYS.Core.Util.Helper;

namespace XYS.Service.Core;

/// <summary>
/// 
/// </summary>
public static class ServiceExtension
{
    /// <summary>
    /// 自动注入服务
    /// </summary>
    /// <returns></returns>
    public static WebApplicationBuilder AddScopedService(this WebApplicationBuilder builder)
    {
        bool hasICurrentUserService = false;
        #region 自动注入Service
        var interfaceServiceTypes = AssemblyHelper.GetAssemblyTypes().Where(t => t.Name.EndsWith("Service") && t.IsInterface).ToList();
        var serviceTypes = AssemblyHelper.GetAssemblyTypes().Where(t => t.Name.EndsWith("Service") && !t.IsAbstract && t.IsClass && !t.IsInterface && t.GetInterfaces().Length > 0).ToList();

        foreach (var serviceType in serviceTypes)
        {
            var interfaceServiceType = interfaceServiceTypes.FirstOrDefault(t => t.FullName == $"{serviceType.Namespace}.I{serviceType.Name}");
            if (interfaceServiceType != null)
            {
                if (serviceType.GetInterface(interfaceServiceType.Name) != null)
                {
                    if (!hasICurrentUserService && interfaceServiceType == typeof(Service.ICurrentUserService)) hasICurrentUserService = true;
                    builder.Services.AddScoped(interfaceServiceType, serviceType);
                }
            }
        }

        #endregion
        if (hasICurrentUserService == false)
        {
            //自动注入 ICurrentUserService
            var currentUserServices = AssemblyHelper.GetAssemblyTypes()
                .Where(t => t.Name.EndsWith("Service") && !t.IsAbstract && t.IsClass && !t.IsInterface && t.GetInterface(typeof(Service.ICurrentUserService).Name) != null)
                .ToList();
            if (currentUserServices.Count == 1)
                builder.Services.AddSingleton(typeof(Service.ICurrentUserService), currentUserServices[0]);
        }
        return builder;
    }
}
